package com.example.gokuplayalong.service.fragments.users.profile;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.custom.CustomLinearLayoutManager;
import com.example.gokuplayalong.bases.custom.textwatcher.CustomLimitInputTextWatcher;
import com.example.gokuplayalong.bases.custom.textwatcher.CustomTextWatcherInterface;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.NetWorkInterface;
import com.example.gokuplayalong.bases.tools.Tools;
import com.example.gokuplayalong.service.fragments.others.UserMainPageAdapter;
import com.example.gokuplayalong.service.fragmentsmanage.BaseFragment;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;
import com.kongzue.dialogx.dialogs.PopTip;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


public class UserMainProfileOnlineCustom extends BaseFragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    View rootView;
    List<Beans> beans = new ArrayList<>();

    UserMainPageAdapter userMainPageAdapter;
    private ImageView mUserMainProfileOnlineCustomIv;
    private RecyclerView mUserMainProfileOnlineCustomRecyclerview;
    private ImageView mUserMainProfileOnlineCustomInputType;
    private EditText mUserMainProfileOnlineCustomInput;
    private TextView mUserMainProfileOnlineCustomInputYuyin;
    private ImageView mUserMainProfileOnlineCustomBiaoqin;
    private ImageView mUserMainProfileOnlineCustomMore;
    private TextView mUserMainProfileOnlineCustomSend;


    public Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {

                    initChanged();
                }
                break;
            }
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_user_main_profile_online_custom, container, false);
        initView();
        return rootView;
    }

    private void initView() {

        mUserMainProfileOnlineCustomIv = rootView.findViewById(R.id.user_main_profile_online_custom_iv);
        mUserMainProfileOnlineCustomRecyclerview = rootView.findViewById(R.id.user_main_profile_online_custom_recyclerview);
        mUserMainProfileOnlineCustomInputType = rootView.findViewById(R.id.user_main_profile_online_custom_inputType);
        mUserMainProfileOnlineCustomInput = rootView.findViewById(R.id.user_main_profile_online_custom_input);
        mUserMainProfileOnlineCustomInputYuyin = rootView.findViewById(R.id.user_main_profile_online_custom_input_yuyin);
        mUserMainProfileOnlineCustomBiaoqin = rootView.findViewById(R.id.user_main_profile_online_custom_biaoqin);
        mUserMainProfileOnlineCustomMore = rootView.findViewById(R.id.user_main_profile_online_custom_more);
        mUserMainProfileOnlineCustomSend = rootView.findViewById(R.id.user_main_profile_online_custom_send);

        CustomLinearLayoutManager customLinearLayoutManager = new CustomLinearLayoutManager(rootView.getContext());
        mUserMainProfileOnlineCustomRecyclerview.setLayoutManager(customLinearLayoutManager);

        userMainPageAdapter = new UserMainPageAdapter(beans);
        mUserMainProfileOnlineCustomRecyclerview.setAdapter(userMainPageAdapter);

        mUserMainProfileOnlineCustomRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int firstVisibleItemPosition = customLinearLayoutManager.findFirstVisibleItemPosition();


                    if (firstVisibleItemPosition == 0 && userMainPageAdapter.getItemCount() % 20 == 0) {
                        AppParams.getInstance().appRunParams.getJsonObject().put("chatNum", AppParams.getInstance().appRunParams.getJsonObject().getIntValue("chatNum") + 1);
                        getChatPageList();
                    }

                }
            }
        });

        mUserMainProfileOnlineCustomInput.addTextChangedListener(new CustomLimitInputTextWatcher(mUserMainProfileOnlineCustomInput, new CustomTextWatcherInterface() {
            @Override
            public void customTextWatch(Editable s) {

            }

            @Override
            public void customTextWatch() {

            }
        }));
        mUserMainProfileOnlineCustomSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (!Tools.Deshak()) return;
                    if (mUserMainProfileOnlineCustomInput.getText().toString().isEmpty()) {
                        PopTip.show("不能发送空内容!");
                        return;
                    }


                    try {
                        Beans beansIn = new Beans();
                        beansIn.getJsonObject().put("phone", AppParams.getInstance().appCurrentUser.getJsonObject().getString("phone"));
                        beansIn.getJsonObject().put("chatObject", "13888888888");
                        beansIn.getJsonObject().put("send", AppParams.getInstance().appCurrentUser.getJsonObject().getString("phone"));
                        beansIn.getJsonObject().put("receive", "13888888888");
                        beansIn.getJsonObject().put("msgStatus", "未读");
                        beansIn.getJsonObject().put("timestamp", Tools.getSDF().format(System.currentTimeMillis()));
                        JSONObject msg = new JSONObject();
                        msg.put("msg", mUserMainProfileOnlineCustomInput.getText().toString());
                        beansIn.getJsonObject().put("msg", msg.toJSONString());
                        AppParams.getNewNetWork().setInterface(new NetWorkInterface() {
                            @SuppressLint("NotifyDataSetChanged")
                            @Override
                            public int success(String msg) {
                                requireActivity().runOnUiThread(new Runnable() {
                                    @SuppressLint("NotifyDataSetChanged")
                                    @Override
                                    public void run() {
                                        try {
                                            JSONObject msgFromServer = JSON.parseObject(msg);
                                            if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                                beansIn.getJsonObject().put("viewType", UserMainPageAdapter.VIEWTYPE_MESSAGE_CHAT);
                                                beans.add(beansIn);
                                                userMainPageAdapter.notifyDataSetChanged();
                                                mUserMainProfileOnlineCustomRecyclerview.scrollToPosition(beans.size() - 1);
                                                mUserMainProfileOnlineCustomInput.setText("");
                                                JSONArray jsonArray = new JSONArray();
                                                JSONObject item = new JSONObject();
                                                item = new JSONObject();
                                                item.put("key", "type");
                                                item.put("value", "聊天消息");
                                                jsonArray.add(item);
                                                item = new JSONObject();
                                                item.put("key", "text");
                                                item.put("value", "我发了一条消息给你");
                                                jsonArray.add(item);
                                                item = new JSONObject();
                                                item.put("key", "sendPhone");
                                                item.put("value", AppParams.getInstance().appCurrentUser.getJsonObject().getString("phone"));
                                                jsonArray.add(item);
                                                //  Publish.getInstance().pushMessageToOne("13888888888", jsonArray.toJSONString());


                                                //客服在线时间 8:00 - 23:00
//                                                GregorianCalendar calendar = new GregorianCalendar();
//                                                if (calendar.get(Calendar.HOUR_OF_DAY) < 8 || calendar.get(Calendar.HOUR_OF_DAY) > 23) {
//                                                    sendMessage("13888888888", AppParams.getInstance().appCurrentUser.getJsonObject().getString("phone"), "你好，客服在线时间：08:00 - 23:00。");
//
//                                                }
                                            }
                                        } catch (Throwable e) {
                                            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                        }
                                    }
                                });
                                return 0;
                            }

                            @Override
                            public int failed(String msg) {
                                return 0;
                            }
                        }).execute(AppParams.getInstance().baseUrl + "/sendMessage", beansIn.getJsonObject().toJSONString());

                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }

                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainProfileOnlineCustomIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchBackOnSysFragment();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initChanged();
        }
    }

    private void initChanged() {
        try {

            AppParams.getInstance().appRunParams.getJsonObject().put("chatNum", 1);
            if (!beans.isEmpty()) beans.clear();

            if (AppParams.getInstance().appRunParams.getJsonObject().getIntValue("firstEnter") == 0) {
                sendMessage("13888888888", AppParams.getInstance().appCurrentUser.getJsonObject().getString("phone"), "您好，客服在线时间：08:00 - 23:00。有任何问题请发送给客服，客服看到会第一时间回复您。");
                AppParams.getInstance().appRunParams.getJsonObject().put("firstEnter", 1);
            }


            getChatPageList();
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    private void getChatPageList() {
        Beans beansIn = new Beans();
        beansIn.getJsonObject().put("phone", AppParams.getInstance().appCurrentUser.getJsonObject().getString("phone"));
        beansIn.getJsonObject().put("chatObject", "13888888888");
        beansIn.getJsonObject().put("chatNum", AppParams.getInstance().appRunParams.getJsonObject().getIntValue("chatNum"));
        beansIn.getJsonObject().put("chatCount", AppParams.getInstance().appRunParams.getJsonObject().getIntValue("chatCount"));
        AppParams.getNewNetWork().setInterface(new NetWorkInterface() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public int success(String msg) {
                requireActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject msgFromServer = JSON.parseObject(msg);
                            if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                if (!beans.isEmpty()) beans.clear();
                                JSONArray chatList = JSON.parseArray(msgFromServer.getString("chatList"));
                                for (int i = 0; i < chatList.size(); i++) {
                                    Beans item = new Beans();
                                    item.setJsonObject(chatList.getJSONObject(i));
                                    item.getJsonObject().put("viewType", UserMainPageAdapter.VIEWTYPE_MESSAGE_CHAT);
                                    beans.add(item);
                                }
                                try {

                                    userMainPageAdapter.notifyDataSetChanged();
                                    int pos = userMainPageAdapter.getItemCount() - (AppParams.getInstance().appRunParams.getJsonObject().getIntValue("chatNum") - 1) * AppParams.getInstance().appRunParams.getJsonObject().getIntValue("chatCount") - 1;
                                    if (pos >= 0 && pos < userMainPageAdapter.getItemCount()) {
                                        mUserMainProfileOnlineCustomRecyclerview.scrollToPosition(pos);
                                    }
                                } catch (Throwable e) {
                                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                }


                                mUserMainProfileOnlineCustomInput.setText("");
                            }
                        } catch (Throwable e) {
                            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                        }
                    }
                });
                return 0;
            }

            @Override
            public int failed(String msg) {
                return 0;
            }
        }).execute(AppParams.getInstance().baseUrl + "/getChatPageList", beansIn.getJsonObject().toJSONString());

    }

    private void sendMessage(String sendPhone, String chatObject, String message) {
        try {
            Beans beansIn = new Beans();
            beansIn.getJsonObject().put("phone", sendPhone);
            beansIn.getJsonObject().put("chatObject", chatObject);
            beansIn.getJsonObject().put("send", sendPhone);
            beansIn.getJsonObject().put("receive", chatObject);
            beansIn.getJsonObject().put("msgStatus", "未读");
            beansIn.getJsonObject().put("timestamp", Tools.getSDF().format(System.currentTimeMillis()));
            JSONObject msg = new JSONObject();
            msg.put("msg", message);
            beansIn.getJsonObject().put("msg", msg.toJSONString());
            AppParams.getNewNetWork().setInterface(new NetWorkInterface() {
                @SuppressLint("NotifyDataSetChanged")
                @Override
                public int success(String msg) {
                    requireActivity().runOnUiThread(new Runnable() {
                        @SuppressLint("NotifyDataSetChanged")
                        @Override
                        public void run() {
                            try {
                                JSONObject msgFromServer = JSON.parseObject(msg);
                                if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                    beansIn.getJsonObject().put("viewType", UserMainPageAdapter.VIEWTYPE_MESSAGE_CHAT);
                                    beans.add(beansIn);
                                    userMainPageAdapter.notifyDataSetChanged();
                                    mUserMainProfileOnlineCustomRecyclerview.scrollToPosition(beans.size() - 1);
                                    mUserMainProfileOnlineCustomInput.setText("");
                                    JSONArray jsonArray = new JSONArray();
                                    JSONObject item = new JSONObject();
                                    item = new JSONObject();
                                    item.put("key", "type");
                                    item.put("value", "聊天消息");
                                    jsonArray.add(item);
                                    item = new JSONObject();
                                    item.put("key", "text");
                                    item.put("value", "我发了一条消息给你");
                                    jsonArray.add(item);
                                    item = new JSONObject();
                                    item.put("key", "sendPhone");
                                    item.put("value", AppParams.getInstance().appCurrentUser.getJsonObject().getString("phone"));
                                    jsonArray.add(item);
                                    //  Publish.getInstance().pushMessageToOne("13888888888", jsonArray.toJSONString());
                                }
                            } catch (Throwable e) {
                                ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                            }
                        }
                    });
                    return 0;
                }

                @Override
                public int failed(String msg) {
                    return 0;
                }
            }).execute(AppParams.getInstance().baseUrl + "/sendMessage", beansIn.getJsonObject().toJSONString());

        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }
}